//
//  BillsListNewViewController.m
//  Thinkape-iOS
//
//  Created by admin on 16/5/31.
//  Copyright © 2016年 TIXA. All rights reserved.
//

#import "BillsListNewViewController.h"
#import "BillsModel.h"
#import "BillListNewCell.h"
#import "BillsDetailViewController.h"
#import "AppDelegate.h"
#import "KindsModel.h"
#import "BillsPickerView.h"
#import "BillsSinglePickView.h"
#import "BillsDatePickView.h"
@interface BillsListNewViewController ()

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftConstraint;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *navHeightConstraints;
@property (weak, nonatomic) IBOutlet UITextField *searchText;

@property (weak, nonatomic) IBOutlet UIButton *expenseBtn;//报销按钮
@property (weak, nonatomic) IBOutlet UIButton *stateBtn;//未完成按钮
@property (weak, nonatomic) IBOutlet UIButton *timeBtn;//最近一周，时间按钮





@property (nonatomic,strong) BillsPickerView *pickerView;
@property (nonatomic,strong) BillsSinglePickView *singlePickView;
@property (nonatomic,strong) BillsDatePickView *datePickView;

@property (nonatomic,strong)KindsModel *selectKindsModel;
@property (nonatomic,strong)KindsMainModel *selectMainModel;
@property (nonatomic,strong)BillsSingleModel *selectSingleModel;
@property (nonatomic,strong)BillsDateModel *selectDatemodel;

@property (nonatomic,strong)NSMutableArray *kindsMainModelArray;
@property (nonatomic,copy)NSString *programId;//传给刷新
@property (nonatomic,strong)UIView *coverView;
@property (nonatomic,copy)NSString *stateValue;//状态的筛选
@property (nonatomic,copy)NSString *dateValue;
@property (nonatomic ,assign)BOOL isSeach;
@end

@implementation BillsListNewViewController
{
    int _p; //页数
    BillsDetailViewController *_billsDetailVC;
    NSInteger _selectTag;//选中按钮的tag,用来区分点击的哪个按钮，并且传回去请求数据
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreshListData];
    }];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    [self.tableView.header beginRefreshing];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navHeightConstraints.constant = 64.0f;
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
- (NSMutableArray *)kindsMainModelArray
{
    if (_kindsMainModelArray == nil) {
        _kindsMainModelArray = [NSMutableArray new];
    }
    return _kindsMainModelArray;
}

#pragma mark -- 请求数据
//刷新：
- (void)refreshListData
{
    _p = 0;
    NSString *url;
    url = [NSString stringWithFormat:@"ac=GetList&u=%@&billtype=ontheway&pi=%d&ps=20",self.uid,_p];

    if (_selectTag == 10) {
        if (_programId) {
            url = [NSString stringWithFormat:@"ac=GetList&u=%@&billtype=ontheway&pi=%d&ps=20&Pid=%@",self.uid,_p,_programId];
        }
//        else{
//            url = [NSString stringWithFormat:@"ac=GetList&u=%@&billtype=ontheway&pi=%d&ps=20",self.uid,_p];
//        }
    }else if (_selectTag == 11){
        if (_stateValue) {
            url = [NSString stringWithFormat:@"ac=GetList&u=%@&billtype=ontheway&pi=%d&ps=20&stvl=%@",self.uid,_p,_stateValue];
        }
//        else{
//            url = [NSString stringWithFormat:@"ac=GetList&u=%@&billtype=ontheway&pi=%d&ps=20",self.uid,_p];
//        }
    }else if (_selectTag == 12){
        if (_dateValue) {
            url = [NSString stringWithFormat:@"ac=GetList&u=%@&billtype=ontheway&pi=%d&ps=20&Stdt=%@",self.uid,_p,_dateValue];
        }
    }
    if (_isSeach) {
        
        url = [NSString stringWithFormat:@"ac=GetList&u=%@&billtype=ontheway&pi=%d&ps=20&Q=%@",self.uid,_p,[_searchText.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
//    }
//    else
        //未完成
//        url = [NSString stringWithFormat:@"ac=%@&u=%@&ukey=%@&pi=%d&ps=20&billtype=ontheway&q=%@",ac,self.uid,self.ukey,p,[_searchText.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    [RequestCenter GetRequest:url
                   parameters:nil
                      success:^(NSURLSessionDataTask *operation, NSDictionary *responseObject) {
                          
                          [self.dataArray removeAllObjects];
                          NSDictionary *dataDic = [responseObject objectForKey:@"msg"];
                          [self.dataArray addObjectsFromArray:[BillsModel objectArrayWithKeyValuesArray:[dataDic objectForKey:@"data"]]];
                          
                          //
                          NSLog(@"改变按钮状态");
                          
                          
                          [self.tableView reloadData];
                          [self.tableView.header endRefreshing];
                          
                      }
                      failure:^(NSURLSessionDataTask *operation, NSError *error) {
                          NSLog(@"错误%@",error);
                          [self.tableView.header endRefreshing];
                      }
            showLoadingStatus:NO];
}
//加载

- (void)loadMoreData
{
    _p += 1;
    
    NSString *url;
    url = [NSString stringWithFormat:@"ac=GetList&u=%@&billtype=ontheway&pi=%d&ps=20",self.uid,_p];
    if (_selectTag == 10) {
        
        if (_programId) {
                url = [NSString stringWithFormat:@"ac=GetList&u=%@&billtype=ontheway&pi=%d&ps=20&Pid=%@",self.uid,_p,_programId];
        }
//            else{
//
//            url = [NSString stringWithFormat:@"ac=GetList&u=%@&billtype=ontheway&pi=%d&ps=20",self.uid,_p];
//        }
        
    }else if (_selectTag == 11){
        
        if (_stateValue) {
            
            url = [NSString stringWithFormat:@"ac=GetList&u=%@&billtype=ontheway&pi=%d&ps=20&stvl=%@",self.uid,_p,_stateValue];
        }
//        else{
//            url = [NSString stringWithFormat:@"ac=GetList&u=%@&billtype=ontheway&pi=%d&ps=20",self.uid,_p];
//        }
    }else if (_selectTag == 12){
        if (_dateValue) {
            url = [NSString stringWithFormat:@"ac=GetList&u=%@&billtype=ontheway&pi=%d&ps=20&Stdt=%@",self.uid,_p,_dateValue];
        }
//        else{
//            
//        
//        }
    }
    if (_isSeach) {
        
        url = [NSString stringWithFormat:@"ac=GetList&u=%@&billtype=ontheway&pi=%d&ps=20&Q=%@",self.uid,_p,[_searchText.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    //未完成
//        url = [NSString stringWithFormat:@"ac=%@&u=%@&ukey=%@&pi=%d&ps=20&billtype=ontheway&q=%@",ac,self.uid,self.ukey,p,[_searchText.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    [RequestCenter GetRequest:url
                   parameters:nil
                      success:^(NSURLSessionDataTask *operation, NSDictionary *responseObject) {
                          NSDictionary *dataDic = [responseObject objectForKey:@"msg"];
                          [self.dataArray addObjectsFromArray:[BillsModel objectArrayWithKeyValuesArray:[dataDic objectForKey:@"data"]]];
                          
                          [self.tableView reloadData];
                          [self.tableView.footer endRefreshing];
                          
                      }
                      failure:^(NSURLSessionDataTask *operation, NSError *error) {
                          [self.tableView.footer endRefreshing];
                      }
            showLoadingStatus:NO];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- ButtonClick 切换
- (IBAction)stateSelect:(UIButton *)sender
{
    for (UIView *subView in self.topView.subviews) {
        
        if ([subView isKindOfClass:[UIButton class]]) {
            UIButton *subBtn = (UIButton *)subView;
            if (subBtn.tag == sender.tag) {
//                subBtn.selected = YES;
                _selectTag = sender.tag;
                
                CGRect frame = self.lineView.frame;
                [UIView animateWithDuration:0.3 animations:^{
                    self.leftConstraint.constant =frame.size.width * (subBtn.tag - 10);
                }];
                //wo
                AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                app.zhuanStr=[NSString stringWithFormat:@"%ld",sender.tag];
                
                switch (sender.tag) {
                    case 10:
                        [self creatPickView];
                        break;
                    case 11:
                        [self creatPickView];
                        
                        break;
                    case 12:
            
                        [self creatPickView];
                        break;
                    default:
                        break;
                }
//                self.pickerView = nil;
//                [self.tableView.header beginRefreshing];
                
            }
            else
                subBtn.selected = NO;
        }
        
    }
}


#pragma mark -- 下面pickView
- (void)creatPickView
{
    _coverView = [[UIView alloc]initWithFrame:self.view.bounds];
    _coverView.backgroundColor = [UIColor grayColor];
    _coverView.alpha = 0.5;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(touchesIncoverView)];
    [_coverView addGestureRecognizer:tapGesture];
    
    [self.view addSubview:_coverView];
    
    if (_selectTag == 10) {
    
        [self.pickerView removeFromSuperview];
        self.pickerView = [[[NSBundle mainBundle]loadNibNamed:@"BillsPickerView" owner:self options:nil]lastObject];
        [self.pickerView setFrame:CGRectMake(0, SCREEN_HEIGHT - 216, SCREEN_WIDTH, 216)];
        __block BillsListNewViewController *weakSelf = self;
        self.pickerView.selectItemCallBack = ^(KindsMainModel *mainModel,KindsModel *model){
            weakSelf.selectKindsModel = model;
            weakSelf.selectMainModel = mainModel;
            weakSelf.pickerView = nil;
//            [weakSelf refreshListData];
            [weakSelf.coverView removeFromSuperview];
            if (model.programid) {
                _programId = model.programid;
                NSString *cname = [model.cname substringToIndex:model.cname.length - 2];
                [weakSelf.expenseBtn setTitle:cname forState:UIControlStateNormal];
            }else if (mainModel.mprogramid){
                _programId = mainModel.mprogramid;
                NSString *cname = mainModel.menuname;
                [weakSelf.expenseBtn setTitle:cname forState:UIControlStateNormal];
            }else{
                _programId = nil;
                
            }
            [weakSelf.tableView.header beginRefreshing];
            
            
        };
        //取消的回调：
        self.pickerView.cancelCallback = ^(){
            
            [weakSelf.coverView removeFromSuperview];
            
        };
    
        [self.view addSubview:self.pickerView];
        [self requestBillsType];
        
    }else if (_selectTag == 11){
       
        [self.singlePickView removeFromSuperview];
        self.singlePickView = [[[NSBundle mainBundle]loadNibNamed:@"BillsSinglePickView" owner:self options:nil]lastObject];
        
        [self.singlePickView setFrame:CGRectMake(0, SCREEN_HEIGHT - 216, SCREEN_WIDTH, 216)];

        [self.view addSubview:self.singlePickView];
     
        __block BillsListNewViewController *weakSelf = self;
        self.singlePickView.selectItemCallBack = ^(BillsSingleModel *model){
           
            [weakSelf.coverView removeFromSuperview];
            weakSelf.selectSingleModel = model;
            weakSelf.singlePickView = nil;
            if (model.Value) {
                _stateValue = model.Value;
            }else{
                _stateValue = nil;
            }
            [weakSelf.stateBtn setTitle:model.Name forState:UIControlStateNormal];
            
            [weakSelf.tableView.header beginRefreshing];
        };

        self.singlePickView.cancelClickBlock = ^(){
            [weakSelf.coverView removeFromSuperview];
            
        };
        
        NSArray *nameArray =@[@"未提交",@"已提交",@"审批中",@"已弃审",@"已退回"];
        NSArray *valueArray = @[@"0",@"1",@"2",@"-1",@"-3"];
        NSMutableArray *modelArray = [NSMutableArray new];
        for (int i = 0; i < nameArray.count; i ++) {
            
            BillsSingleModel *model = [[BillsSingleModel alloc]init];
            model.Name = nameArray[i];
            model.Value = valueArray[i];
            model.Isopen = @"1";
            [modelArray addObject:model];
            
        }
        BillsSingleModel *allModel = [[BillsSingleModel alloc]init];
        allModel.Name = @"全部";
        [modelArray addObject:allModel];
        
        self.singlePickView.dataArray = modelArray;
        
    }else if (_selectTag == 12){
        [self.datePickView removeFromSuperview];
        [self.pickerView removeFromSuperview];
        [self.singlePickView removeFromSuperview];
        self.datePickView = [[[NSBundle mainBundle]loadNibNamed:@"BillsDatePickView" owner:self options:nil]lastObject];
        
        [self.datePickView setFrame:CGRectMake(0, SCREEN_HEIGHT - 216, SCREEN_WIDTH, 216)];
        
        [self.view addSubview:self.datePickView];
        
        __block BillsListNewViewController *weakSelf = self;
        self.datePickView.selectItemCallBack = ^(BillsDateModel *model){
            
            [weakSelf.coverView removeFromSuperview];
            weakSelf.selectDatemodel = model;
   
            if (model.date) {
                weakSelf.dateValue = model.date;
                [weakSelf.timeBtn setTitle:model.name forState:UIControlStateNormal];
            }else{
                [weakSelf.timeBtn setTitle:@"全部" forState:UIControlStateNormal];
            }
           
            [weakSelf.tableView.header beginRefreshing];
        };
        
        self.datePickView.cancelClickBlock = ^(){
            [weakSelf.coverView removeFromSuperview];
            
        };
        
        
        /**
         *  获取时间
         *
         *  @return     NSDate *date = [NSDate date];
         NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
         formatter.dateFormat = @"yyyy年MM月dd日";
         self.time.text = [formatter stringFromDate:date];
         */
        
        NSDate *date = [NSDate date];
        NSArray *dateArray = @[@"一周内",@"一个月内",@"更多"];
        NSMutableArray *dateMutArray = [NSMutableArray new];
        for (int i = 0; i < dateArray.count; i ++) {
            BillsDateModel *dateModel = [BillsDateModel new];
            dateModel.name = dateArray[i];
            if (i == 0) {
                dateModel.date = [self calculateDateWithParameter:0];
            }else if (i == 1){
                dateModel.date = [self calculateDateWithParameter:1];
            }else{
                dateModel.date = nil;
            }
            
            [dateMutArray addObject:dateModel];
        }
        
        self.datePickView.dataArray = dateMutArray;
    }
}

- (void)touchesIncoverView
{
    [self.pickerView removeFromSuperview];
    [self.datePickView removeFromSuperview];
    [self.singlePickView removeFromSuperview];
    [self.coverView removeFromSuperview];

}


//计算日期
- (NSString *)calculateDateWithParameter:(NSInteger )number
{
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = nil;
    comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];
    NSDateComponents *adcomps = [[NSDateComponents alloc] init];
    if (number == 0) {
        [adcomps setYear:0];
        [adcomps setMonth:0];
        [adcomps setDay:-7];
    }else if (number == 1){
        [adcomps setYear:0];
        [adcomps setMonth:-1];
        [adcomps setDay:0];
    }
 
    NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:date options:0];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy/MM/dd";
    NSString *newDateStr = [formatter stringFromDate:newdate];
    return newDateStr;
}

//pickView出现的时候请求pickView里面的数据：
- (void)requestBillsType{
    //http://27.115.23.126:3032/ashx/mobilenew.ashx?ac=GetSspBillType&u=1
    
    NSString *strUrl = [NSString stringWithFormat:@"ac=GetMenuList&u=%@",self.uid];
    [RequestCenter GetRequest:strUrl
                   parameters:nil
                      success:^(NSURLSessionDataTask *operation, NSDictionary *responseObject) {
                          
                          [self.kindsMainModelArray removeAllObjects];
                          NSMutableArray *array = [KindsMainModel objectArrayWithKeyValuesArray:[[responseObject objectForKey:@"msg"] objectForKey:@"data"]];
                          
                          KindsMainModel *mainModel = [[KindsMainModel alloc]init];
                          mainModel.menuname = @"全部";
                          mainModel.mprogramid = @"";
                          
                          [array addObject:mainModel];

                          for (KindsMainModel *model in array) {
                              NSArray *array0;
                              if (model.ldata) {
                                 array0 = model.ldata;
                              }else{
                                  array0 = [NSArray array];
                              }
                         
                              NSMutableArray *array1 = [KindsModel objectArrayWithKeyValuesArray:array0];
                              NSLog(@"");
                              
                              KindsModel *kindsModel = [[KindsModel alloc]init];
                              kindsModel.cname = @"全部";
                            
                              [array1 addObject:kindsModel];
                              [self.kindsMainModelArray addObject:array1];
                              
                          }
                
                          [SVProgressHUD dismiss];
                          
                          self.pickerView.titleArr = array;
                          self.pickerView.dataArray = self.kindsMainModelArray;
                        
                      }
                      failure:^(NSURLSessionDataTask *operation, NSError *error) {
                         
                          [SVProgressHUD showErrorWithStatus:@"网络错误，请稍后再试"];
                          
                          
                      }];
}





#pragma mark -- TableViewDelegate && TableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *cellid = @"billNewCell";
    BillListNewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    
    BillsModel *model = [self.dataArray safeObjectAtIndex:indexPath.row];
    cell.billNum.text = model.billno;
    cell.billPrice.text = [NSString stringWithFormat:@"￥%@",model.billmoney];
    cell.billName.text = model.pagename;
    cell.tilenamece.text = [NSString stringWithFormat:@"%@-%@",model.deptid,model.uid];
    NSString *mobile = model.savesourcetype;
    if ([mobile isEqual:@"Mobile"]) {
        cell.billslabel.text=@"(移动)";
    }else{
        cell.billslabel.text = @"(电脑)";
    }
    
    //cell.billslabel.text = [NSString stringWithFormat:@" (%@)",model.];
    NSString *str = [model.pagename substringToIndex:1];
    cell.billTime.text = model.opdate;
    cell.nameLabel.text = [NSString stringWithFormat:@"%@  %@",model.uid,model.deptid];
    cell.billProcess.text = model.flowstatus.length > 0 ? model.flowstatus : @"";
    
    if ([str isEqualToString:@"差"]) {
        cell.billTypeImage.image = [UIImage imageNamed:@"chailv.jpg"];
    }
    else if ([str isEqualToString:@"招"]) {
        cell.billTypeImage.image = [UIImage imageNamed:@"zhaodai.jpg"];
    }
    
    else if ([str isEqualToString:@"普"]) {
        cell.billTypeImage.image = [UIImage imageNamed:@"putong.jpg"];
    }
    else if ([str isEqualToString:@"借"]){
        cell.billTypeImage.image = [UIImage imageNamed:@"jiekuan.jpg"];
    }
    else {
        cell.billTypeImage.image = [UIImage imageNamed:@"qita.jpg"];
    }
    
    cell.titleLabel.text = str;

    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    BillsDetailViewController *detailVC = [self.storyboard instantiateViewControllerWithIdentifier:@"BillsDetail"];
    BillsModel *model = [self.dataArray objectAtIndex:indexPath.row];
    detailVC.billid     = model.billid;
    detailVC.programeId = model.programid;
    detailVC.flowid     = model.flowid;
    detailVC.bills      = model;
    detailVC.reloadData = ^(){
        [self.tableView.header beginRefreshing];
    };
    //wo 未完成列表的审核状态
    AppDelegate * app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    app.flowstatus=model.flowstatus;
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (IBAction)goback:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)doSearchBills:(id)sender {
    _isSeach = YES;
    [self.tableView.header beginRefreshing];
    [_searchText resignFirstResponder];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    _isSeach = YES;
    [self.tableView.header beginRefreshing];
    [_searchText resignFirstResponder];
    return YES;
}

- (IBAction)seachBills:(id)sender {
    if (self.navHeightConstraints.constant == 64.0f) {
        self.navHeightConstraints.constant += 40.0f;
    }
    else
    {
        self.navHeightConstraints.constant -= 40.0f;
    }
}




@end
